package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.drawable.IconCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.shortcut.ShortcutHelper;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.AllReplaceAdapter;
import flc.ast.adapter.SelAppAdapter;
import flc.ast.bean.MyAppBean;
import flc.ast.bean.MyReplaceBean;
import flc.ast.databinding.ActivityAllReplaceBinding;
import flc.ast.dialog.ShortcutCreateDialog;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.ToastUtil;
import stark.common.basic.view.container.StkRecycleView;
import stark.common.bean.StkResBean;

public class AllReplaceActivity extends BaseAc<ActivityAllReplaceBinding> {

    public static List<StkResBean> sIconList;
    List<MyReplaceBean> mReplacelist=new ArrayList<>();
    private AllReplaceAdapter replaceAdapter;
    private Dialog mySelAppDialog;
    private SelAppAdapter selAppAdapter;
    private int selPosition=0;
    private LinearLayoutManager linearLayoutManager;
    private boolean notNull=false;


    @Override
    protected int onCreate() {
        return R.layout.activity_all_replace;
    }

    @Override
    protected void initView() {
        mDataBinding.ivAllReplaceBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivApplyIcon.setOnClickListener(this);
        for (StkResBean bean : sIconList) {
            mReplacelist.add(new MyReplaceBean(bean.getUrl(),null,""));
        }
        linearLayoutManager=new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false);
        mDataBinding.rvReplaceList.setLayoutManager(linearLayoutManager);
        replaceAdapter=new AllReplaceAdapter();
        mDataBinding.rvReplaceList.setAdapter(replaceAdapter);
        replaceAdapter.setList(mReplacelist);
        replaceAdapter.addChildClickViewIds(R.id.ivChooseImage);
        replaceAdapter.setOnItemChildClickListener(this);
        //app选择弹框
        selAppDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivDialogSelAppCancel:
                mySelAppDialog.dismiss();
                break;
            case R.id.ivApplyIcon://应用图标
                for (int i = 0; i < mReplacelist.size(); i++) {
                    if (mReplacelist.get(i).getBean()!=null){
                        View view=linearLayoutManager.findViewByPosition(i);
                        EditText et=view.findViewById(R.id.etName);
                        String name=et.getText().toString();
                        if (TextUtils.isEmpty(name)){
                            ToastUtils.showShort(getString(R.string.please_input_name));
                            return;
                        }
                        notNull=true;
                    }
                }
                if (notNull){
                    showCreateDialog();
                }
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter==selAppAdapter){
            MyAppBean bean=selAppAdapter.getItem(position);
            mReplacelist.get(selPosition).setBean(bean);
            replaceAdapter.setList(mReplacelist);
            mySelAppDialog.dismiss();
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        if (adapter==replaceAdapter){
            switch (view.getId()){
                case R.id.ivChooseImage:
                    mySelAppDialog.show();
                    selPosition=position;
                    break;
            }
        }
    }

    @Override
    protected void initData() {

    }

    //app选择弹框
    private void selAppDialog() {
        mySelAppDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_app, null);
        mySelAppDialog.setContentView(inflate);
        mySelAppDialog.setCancelable(true);
        Window dialogWindow = mySelAppDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogSelAppCancel);
        StkRecycleView recycleView=inflate.findViewById(R.id.rvAppList);
        cancel.setOnClickListener(this);
        recycleView.setLayoutManager(new GridLayoutManager(mContext,4));
        selAppAdapter=new SelAppAdapter();
        recycleView.setAdapter(selAppAdapter);
        selAppAdapter.setOnItemClickListener(this);
        getAllAppData();
    }

    private void getAllAppData() {
        List<MyAppBean> mMyAppBeanList=new ArrayList<>();
        RxUtil.create(new RxUtil.Callback<List<PackageInfo>>() {
            @Override
            public void doBackground(ObservableEmitter<List<PackageInfo>> emitter) {
                List<PackageInfo> installedPackageInfoList = mContext.getPackageManager()
                        .getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);
                emitter.onNext(installedPackageInfoList);
            }

            @Override
            public void accept(List<PackageInfo> infoList) {
                if (infoList != null && infoList.size() != 0) {
                    for (PackageInfo packageInfo : infoList) {
                        mMyAppBeanList.add(new MyAppBean(packageInfo.packageName, packageInfo.applicationInfo.sourceDir, false));
                    }
                    selAppAdapter.setList(mMyAppBeanList);
                }
            }
        });

    }

    private ShortcutCreateDialog mDialog;


    private void showCreateDialog() {
        mDialog = new ShortcutCreateDialog(this);
        mDialog.show();
        mDialog.setListener(new ShortcutCreateDialog.Ilistener() {
            @Override
            public void clickConfirm() {
                showDialog(getString(R.string.set_ing));
                for (int i = 0; i < mReplacelist.size(); i++) {
                    if (mReplacelist.get(i).getBean()!=null){
                        View view=linearLayoutManager.findViewByPosition(i);
                        EditText et=view.findViewById(R.id.etName);
                        String name=et.getText().toString();
                        if (TextUtils.isEmpty(name)){
                            ToastUtils.showShort(getString(R.string.please_input_name));
                            return;
                        }
                        ImageView iv=view.findViewById(R.id.ivIconSrc);
                        IconCompat iconCompat;
                        iconCompat = IconCompat.createWithBitmap(ImageUtils.view2Bitmap(iv));
                        int finalI = i;
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                ShortcutHelper.installShortCut(name, iconCompat, mReplacelist.get(finalI).getBean().getName());
                            }
                        },1000);
                    }
                }
                dismissDialog();
                ToastUtils.showShort(getString(R.string.set_suc));
            }
        });
    }

}